/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * sniffer.c
 * Copyright (C) chemek anouar 2012 <anouar.chemek@esprit.tn>
 *
 * WiScramb is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * WiScramb is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "sniffer.h"

struct sockaddr_ll sll;
int sock_fd;
ssize_t buffer_len;

/**
 * create_raw_socket - create raw socket, the file descriptor result is sock_fd
 * Returns: 0 on success -1 on fail
 */
int create_raw_socket (void)
{
  /*Try to open socket*/
  sock_fd = socket ( AF_PACKET, SOCK_RAW, htons ( ETH_P_ALL ) );
  if ( sock_fd != -1 )
    return (0);
  return (-1);
}

/**
 * set_device_ll - set the sll struct with the specific lower layer interface
 * @sll:The sockaddr_ll is a device independent physical layer address
 * Returns: void
 */
void set_device_ll ( void )
{
  memset ( &sll, 0, sizeof ( sll ) );
  sll.sll_family = PF_PACKET ;
  sll.sll_ifindex = if_nametoindex ( "mon0" );
  sll.sll_halen = 0;
}

/**
 * bind_socket_to_ll - bind the created raw socket to a specified lower layer interface
 * Returns: void
 */
void bind_socket_to_ll ( void )
{
  if (bind(sock_fd,  ( struct sockaddr  *)&sll, sizeof(sll)) == -1) {
      perror( "Erreur avec bind\n" );
  }
}

/**
 * configure_raw_socket - Configure a raw Socket
 * create the raw socket and bind it to the lower layer interface
 * Returns: 0 on success -1 on fail
 * The sockaddr_ll is a device independent physical layer address
 */
int configure_raw_socket (void)
{
  if(create_raw_socket () == -1){
      perror("erreur creation socket");
  }
  set_device_ll ();
  bind_socket_to_ll();
  return (0);

}

/**
 * ieee80211_frame_sniff - Sniff one frame by using the attached raw socket to the ll interface
 * @buffer:The received buffer at lower layer (receivfrom call result)
 * @sock_fd: The file descriptor related to the created raw socket
 * Returns: void
 * The sockaddr_ll is a device independent physical layer address
 */
void ieee80211_frame_sniff (char *buffer,int sock_fd)
{
  buffer_len = recvfrom ( sock_fd, buffer, BUF_SIZE, 0, NULL, NULL );
}




